import { Config } from './config.js';
export function Http(params) {
	return new Promise((resolved, rejected) => {
		var options = {};
		
		options.method = params.type ? params.type : 'GET';
		
		options.header = {
			'Accept': 'application/json',
			'content-type': options.method === 'POST' ? 'application/x-www-form-urlencoded' : 'application/json'
		};
		
		options.url = Config.http_domain + Config.http_api[params.url];
		
		// 如果请求地址后面需添扩展其他路径，则需要重新组装地址
		if (params.urlextend) {
			options.url = options.url + '/' + params.urlextend
		}
		
		// 如果请求地址是完整的链接或外链，就直接读取url,不需要组装地址
		if (params.urlfull) {
		  options.url = params.url;
		}
		
		options.data = params.data ? params.data : {};
		
		// 接口请求是否需要传入token
		if (params.token) {
			let $token = uni.getStorageSync('token')
			if ($token) {
				options.data.token = $token
			}
		}

		// 接口请求是否显示加载状态
		if (params.load) {
			uni.showLoading({ title: '加载中', mask: true });
		}

		// 接口调用成功
		options.success = (res) => {
			if (params.load) {
				uni.hideLoading();
			}
			// 判断以2（2xx)开头的状态码为正确
			var code = res.statusCode.toString();
			var startChar = code.charAt(0);
			if (startChar == '2') {
				resolved(res.data);
			}
			if (res.statusCode == 401 || res.statusCode == 402) {
				let content = res.data.code == 401 ? '请先登录后再操作' : '登录信息已过期,请重新登录';
				uni.showModal({
					title: '登录提示',
					confirmText: '去登录',
					confirmColor: '#03004c',
					cancelText: '首页',
					content: content,
					success: function(res) {
						if (res.confirm) {
							let pages = getCurrentPages(); // 获取栈实例
							let page = pages[pages.length - 1]; // 获取当前页面的数据，包含页面路由

							let query = page.options;
							let path = page.route;
							let fullPath = '';
							
							if (JSON.stringify(query) == "{}") {
								fullPath = path
							} else {
								let num = 0
								for (let key in query) {
									num++
									if (num > 1) {
										fullPath = path + '&' + key + '=' + query[key]
									} else {
										fullPath = path + '?' + key + '=' + query[key]
									}
								}
							}
							
							let returnurl = {
								path: '/' + path,
								fullPath: '/' + fullPath,
								query: query
							}
							
							uni.setStorage({ key: 'returnurl', data: returnurl })
							uni.redirectTo({ url: '/pages/common/login' });
						}
						if (res.cancel) {
							uni.reLaunch({ url: '/pages/home/index' });
						}
						uni.removeStorageSync('userInfo');
					}
				});
			}
			if (res.statusCode == 500) {
				resolved({code: res.statusCode});
			}
		}
		
		// 接口调用失败
		options.fail = (err) => {
			rejected(err);
		}
		
		uni.request(options);
	});
}
